import React, { useState, useEffect } from 'react';
import { Trigger, Image } from '@arco-design/web-react';
import { ScrollList, ScrollItem } from '@douyinfe/semi-ui';
import { IconClose, IconMinus } from '@douyinfe/semi-icons';
import clock from '@/assets/images/clock.svg';
import styles from './index.module.scss';

const TimeRangeSelector = ({ 
    startTime = '0:00:00:00', 
    endTime = '0:00:00:00', 
    onStartTimeChange, 
    onEndTimeChange,
    disabled = false,
    current
}) => {
    // 获取视频时长
    const [videoDuration, setVideoDuration] = useState(null);
    
    useEffect(() => {
        const video = document.querySelector('video');
        if (video) {
            const updateDuration = () => {
                if (video.duration && !isNaN(video.duration)) {
                    setVideoDuration(video.duration);
                }
            };
            
            // 如果视频已经加载完成
            if (video.duration && !isNaN(video.duration)) {
                setVideoDuration(video.duration);
            }
            
            // 监听视频加载完成事件
            video.addEventListener('loadedmetadata', updateDuration);
            video.addEventListener('durationchange', updateDuration);
            
            return () => {
                video.removeEventListener('loadedmetadata', updateDuration);
                video.removeEventListener('durationchange', updateDuration);
            };
        }
    }, []);
    
    // 将视频时长转换为时分秒毫秒格式
    const getMaxTime = () => {
        if (!videoDuration) return { hour: 23, minute: 59, second: 59, millisecond: 99 };
        
        const totalSeconds = Math.floor(videoDuration);
        const hours = Math.floor(totalSeconds / 3600);
        const minutes = Math.floor((totalSeconds % 3600) / 60);
        const seconds = totalSeconds % 60;
        const milliseconds = Math.floor((videoDuration - totalSeconds) * 1000);
        
        return {
            hour: hours,
            minute: minutes,
            second: seconds,
            millisecond: Math.min(milliseconds, 999)
        };
    };
    const [startTimeVisible, setStartTimeVisible] = useState(false);
    const [endTimeVisible, setEndTimeVisible] = useState(false);
    
    // 时间选择器状态
    const [selectStartHour, setSelectStartHour] = useState(0);
    const [selectStartMinutes, setSelectStartMinutes] = useState(0);
    const [selectStartSeconds, setSelectStartSeconds] = useState(0);
    const [selectStartMilliSeconds, setSelectStartMilliSeconds] = useState(0);
    
    const [selectEndHour, setSelectEndHour] = useState(0);
    const [selectEndMinutes, setSelectEndMinutes] = useState(0);
    const [selectEndSeconds, setSelectEndSeconds] = useState(0);
    const [selectEndMilliSeconds, setSelectEndMilliSeconds] = useState(0);
    
    // 时间数据状态
    const [startHours, setStartHours] = useState([]);
    const [startMinutes, setStartMinutes] = useState([]);
    const [startSeconds, setStartSeconds] = useState([]);
    const [startMilliSeconds, setStartMilliSeconds] = useState([]);
    
    const [endHours, setEndHours] = useState([]);
    const [endMinutes, setEndMinutes] = useState([]);
    const [endSeconds, setEndSeconds] = useState([]);
    const [endMilliSeconds, setEndMilliSeconds] = useState([]);
    
    // 基础时间数据
    const hours = new Array(24).fill(0).map((itm, index) => ({
        value: index,
    }));
    const minutes = new Array(60).fill(0).map((itm, index) => ({
        value: index,
    }));
    const seconds = new Array(60).fill(0).map((itm, index) => ({
        value: index,
    }));
    const milliSeconds = new Array(1000).fill(0).map((itm, index) => ({
        value: index,
    }));
    
    // 解析时间字符串
    const parseTime = (timeStr) => {
        const parts = timeStr.split(/[:.,]/);
        return {
            hour: parseInt(parts[0]) || 0,
            minute: parseInt(parts[1]) || 0,
            second: parseInt(parts[2]) || 0,
            millisecond: parseInt(parts[3]) || 0
        };
    };
    
    // 初始化时间选择器状态
    useEffect(() => {
        const startParsed = parseTime(startTime);
        setSelectStartHour(startParsed.hour);
        setSelectStartMinutes(startParsed.minute);
        setSelectStartSeconds(startParsed.second);
        setSelectStartMilliSeconds(startParsed.millisecond);
        
        const endParsed = parseTime(endTime);
        setSelectEndHour(endParsed.hour);
        setSelectEndMinutes(endParsed.minute);
        setSelectEndSeconds(endParsed.second);
        // 如果开始时间和结束时间相同，结束时间的毫秒不选中
        setSelectEndMilliSeconds(startTime === endTime ? 1 : endParsed.millisecond);
    }, [startTime, endTime]);
    
    // 时间限制逻辑
    useEffect(() => {
        const maxTime = getMaxTime();
        
        // 开始时间小时限制：不能大于结束时间小时，也不能超过视频时长
        setStartHours(hours.map((item, index) => {
            let disabled = false;
            if (index > selectEndHour || index > maxTime.hour) {
                disabled = true;
            }
            return { ...item, disabled: disabled };
        }));
        
        // 结束时间小时限制：不能小于开始时间小时，也不能超过视频时长
        setEndHours(hours.map((item, index) => {
            let disabled = false;
            if (index < selectStartHour || index > maxTime.hour) {
                disabled = true;
            }
            return { ...item, disabled: disabled };
        }));
        
        // 开始时间分钟限制
        setStartMinutes(minutes.map((item, index) => {
            let disabled = false;
            if (selectStartHour == selectEndHour && index > selectEndMinutes) {
                disabled = true;
            }
            // 如果是最大小时，分钟不能超过视频时长的分钟
            if (selectStartHour == maxTime.hour && index > maxTime.minute) {
                disabled = true;
            }
            return { ...item, disabled: disabled };
        }));
        
        // 结束时间分钟限制
        setEndMinutes(minutes.map((item, index) => {
            let disabled = false;
            if (selectStartHour == selectEndHour && index < selectStartMinutes) {
                disabled = true;
            }
            // 如果是最大小时，分钟不能超过视频时长的分钟
            if (selectEndHour == maxTime.hour && index > maxTime.minute) {
                disabled = true;
            }
            return { ...item, disabled: disabled };
        }));
        
        // 开始时间秒钟限制
        setStartSeconds(seconds.map((item, index) => {
            let disabled = false;
            if (selectStartHour == selectEndHour && selectStartMinutes == selectEndMinutes && index > selectEndSeconds) {
                disabled = true;
            }
            // 如果是最大小时和分钟，秒钟不能超过视频时长的秒钟
            if (selectStartHour == maxTime.hour && selectStartMinutes == maxTime.minute && index > maxTime.second) {
                disabled = true;
            }
            return { ...item, disabled: disabled };
        }));
        
        // 结束时间秒钟限制
        setEndSeconds(seconds.map((item, index) => {
            let disabled = false;
            if (selectStartHour == selectEndHour && selectStartMinutes == selectEndMinutes && index < selectStartSeconds) {
                disabled = true;
            }
            // 如果是最大小时和分钟，秒钟不能超过视频时长的秒钟
            if (selectEndHour == maxTime.hour && selectEndMinutes == maxTime.minute && index > maxTime.second) {
                disabled = true;
            }
            return { ...item, disabled: disabled };
        }));
        
        // 开始时间毫秒限制
        setStartMilliSeconds(milliSeconds.map((item, index) => {
            let disabled = false;
            if (selectStartHour == selectEndHour && selectStartMinutes == selectEndMinutes && selectStartSeconds == selectEndSeconds && index >= selectEndMilliSeconds) {
                disabled = true;
            }
            // 如果是最大小时、分钟和秒钟，毫秒不能超过视频时长的毫秒
            if (selectStartHour == maxTime.hour && selectStartMinutes == maxTime.minute && selectStartSeconds == maxTime.second && index > maxTime.millisecond) {
                disabled = true;
            }
            return { ...item, disabled: disabled };
        }));
        
        // 结束时间毫秒限制
        setEndMilliSeconds(milliSeconds.map((item, index) => {
            let disabled = false;
            if (selectStartHour == selectEndHour && selectStartMinutes == selectEndMinutes && selectStartSeconds == selectEndSeconds && index <= selectStartMilliSeconds) {
                disabled = true;
            }
            // 如果是最大小时、分钟和秒钟，毫秒不能超过视频时长的毫秒
            if (selectEndHour == maxTime.hour && selectEndMinutes == maxTime.minute && selectEndSeconds == maxTime.second && index > maxTime.millisecond) {
                disabled = true;
            }
            return { ...item, disabled: disabled };
        }));
    }, [selectStartHour, selectEndHour, selectStartMinutes, selectEndMinutes, selectStartSeconds, selectEndSeconds, selectStartMilliSeconds, selectEndMilliSeconds, videoDuration]);

    const handleStartTimeClick = () => {
        if (!disabled) {
            setStartTimeVisible(!startTimeVisible);
        }
    };

    const handleEndTimeClick = () => {
        if (!disabled) {
            setEndTimeVisible(!endTimeVisible);
        }
    };
    
    // 时间选择处理
    const selectTime = (value, type) => {
        switch (type) {
            case "startHour":
                setSelectStartHour(value.value);
                break;
            case "startMinutes":
                setSelectStartMinutes(value.value);
                break;
            case "startSeconds":
                setSelectStartSeconds(value.value);
                break;
            case "startMilliSeconds":
                setSelectStartMilliSeconds(value.value);
                break;
            case "endHour":
                setSelectEndHour(value.value);
                break;
            case "endMinutes":
                setSelectEndMinutes(value.value);
                break;
            case "endSeconds":
                setSelectEndSeconds(value.value);
                break;
            case "endMilliSeconds":
                setSelectEndMilliSeconds(value.value);
                break;
            default:
                break;
        }
    };
    
    // 格式化时间
    const formatTime = (h, m, s, ms) => {
        const formatHour = (num) => num.toString(); // 小时不补0
        const formatNum = (num) => num.toString().padStart(2, '0');
        const formatMs = (num) => num.toString().padStart(2, '0');
        return `${formatHour(h)}:${formatNum(m)}:${formatNum(s)}:${formatMs(ms)}`;
    };
    
    // 确认时间选择
    const confirmTimeSelection = (type) => {
        if (type === 'start') {
            const newStartTime = formatTime(selectStartHour, selectStartMinutes, selectStartSeconds, selectStartMilliSeconds);
            onStartTimeChange && onStartTimeChange(newStartTime);
            setStartTimeVisible(false);
        } else {
            const newEndTime = formatTime(selectEndHour, selectEndMinutes, selectEndSeconds, selectEndMilliSeconds);
            onEndTimeChange && onEndTimeChange(newEndTime);
            setEndTimeVisible(false);
        }
    };
    
    // 取消时间选择
    const cancelTimeSelection = (type) => {
        if (type === 'start') {
            const startParsed = parseTime(startTime);
            setSelectStartHour(startParsed.hour);
            setSelectStartMinutes(startParsed.minute);
            setSelectStartSeconds(startParsed.second);
            setSelectStartMilliSeconds(startParsed.millisecond);
            setStartTimeVisible(false);
        } else {
            const endParsed = parseTime(endTime);
            setSelectEndHour(endParsed.hour);
            setSelectEndMinutes(endParsed.minute);
            setSelectEndSeconds(endParsed.second);
            setSelectEndMilliSeconds(startTime === endTime ? 1 : endParsed.millisecond);
            setEndTimeVisible(false);
        }
    };

    const renderTimePopup = () => {
        const scrollHeader = (
            <div className={styles.scrollHeaderWrap}>
                <div>时间范围选择</div>
                <div className={styles.closeBtn} onClick={() => {
                    cancelTimeSelection('start');
                    cancelTimeSelection('end');
                }}>
                    <IconClose />
                </div>
            </div>
        );
        
        const scrollFooter = (
            <div className={styles.scrollFooterWrap}>
                <div className={`${styles.cancelButton} ${styles.itemBtn}`} onClick={() => {
                    cancelTimeSelection('start');
                    cancelTimeSelection('end');
                }}>取消</div>
                <div className={`${styles.okButton} ${styles.itemBtn}`} onClick={() => {
                    confirmTimeSelection('start');
                    confirmTimeSelection('end');
                }}>确认</div>
            </div>
        );
        
        return (
            <ScrollList className={styles.scrollListWrap} header={scrollHeader} footer={scrollFooter}>
                <ScrollItem
                    mode="wheel"
                    cycled={true}
                    list={startHours}
                    className={styles.scrollItem}
                    selectedIndex={selectStartHour}
                    onSelect={(value) => selectTime(value, "startHour")}
                />
                <div className={styles.splitIcon}>:</div>
                <ScrollItem
                    mode="wheel"
                    cycled={true}
                    list={startMinutes}
                    className={styles.scrollItem}
                    selectedIndex={selectStartMinutes}
                    onSelect={(value) => selectTime(value, "startMinutes")}
                />
                <div className={styles.splitIcon}>:</div>
                <ScrollItem
                    mode="wheel"
                    cycled={true}
                    list={startSeconds}
                    className={styles.scrollItem}
                    selectedIndex={selectStartSeconds}
                    onSelect={(value) => selectTime(value, "startSeconds")}
                />
                <div className={styles.splitIcon}>:</div>
                <ScrollItem
                    mode="wheel"
                    cycled={true}
                    list={startMilliSeconds}
                    className={styles.scrollItem}
                    selectedIndex={selectStartMilliSeconds}
                    onSelect={(value) => selectTime(value, "startMilliSeconds")}
                />
                <div className={styles.splitStr}>
                    <IconMinus />
                </div>
                <ScrollItem
                    mode="wheel"
                    cycled={true}
                    list={endHours}
                    className={styles.scrollItem}
                    selectedIndex={selectEndHour}
                    onSelect={(value) => selectTime(value, "endHour")}
                />
                <div className={styles.splitIcon}>:</div>
                <ScrollItem
                    mode="wheel"
                    cycled={true}
                    list={endMinutes}
                    className={styles.scrollItem}
                    selectedIndex={selectEndMinutes}
                    onSelect={(value) => selectTime(value, "endMinutes")}
                />
                <div className={styles.splitIcon}>:</div>
                <ScrollItem
                    mode="wheel"
                    cycled={true}
                    list={endSeconds}
                    className={styles.scrollItem}
                    selectedIndex={selectEndSeconds}
                    onSelect={(value) => selectTime(value, "endSeconds")}
                />
                <div className={styles.splitIcon}>:</div>
                <ScrollItem
                    mode="wheel"
                    cycled={true}
                    list={endMilliSeconds}
                    className={styles.scrollItem}
                    selectedIndex={selectEndMilliSeconds}
                    onSelect={(value) => selectTime(value, "endMilliSeconds")}
                />
            </ScrollList>
        );
    };

    return (
        <div className={styles.timeRangeSelector}>
            <Trigger 
                popup={() => renderTimePopup()} 
                trigger='manual' 
                position={startTimeVisible ? 'bl' : 'br'}
                popupVisible={!disabled && (startTimeVisible || endTimeVisible)}
                onVisibleChange={(visible) => {
                    if (!visible) {
                        cancelTimeSelection('start');
                        cancelTimeSelection('end');
                    }
                }}
            >
                <div className={styles.timeRangeDisplay}>
                    <span 
                        className={`${styles.timeItem} ${disabled ? styles.disabled : ''}`}
                        onClick={handleStartTimeClick}
                    >
                        <div className={styles.timeText}>{startTime}</div>
                        <Image 
                            draggable={false} 
                            src={clock} 
                            preview={false} 
                            className={styles.clockIcon}
                        />
                    </span>
                    
                    <span className={styles.separator}>到</span>
                    
                    <span 
                        className={`${styles.timeItem} ${disabled ? styles.disabled : ''}`}
                        onClick={handleEndTimeClick}
                    >
                        <div className={styles.timeText}>{endTime}</div>
                        <Image 
                            draggable={false} 
                            src={clock} 
                            preview={false} 
                            className={styles.clockIcon}
                        />
                    </span>
                </div>
            </Trigger>
        </div>
    );
};

export default TimeRangeSelector;